import json
import logging
from flask import Flask, request, jsonify
from paddleocr import PaddleOCR
#python -m pip install paddlepaddle==2.5.1 -i https://pypi.tuna.tsinghua.edu.cn/simple
#pip install "paddleocr>=2.7.0" -i https://mirror.baidu.com/pypi/simple

def init_log():
    #设置打印格式和等级
    logging.basicConfig(format='%(asctime)s %(filename)s %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S',
                        level=logging.INFO)
    file_handler = logging.FileHandler('ocr.log', encoding='utf-8')
    #设置输出等级
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    logger = logging.getLogger()
    logger.handlers.append(file_handler)

init_log()

#name 是python中的特殊变量 如果文件作为主体程序执行 那么__name__的值就是__main__ 如果是被其他模块引入那么__name__就是模块名称
app = Flask(__name__)

#创建一个PaddleOCR对象 使用方向识别器 不使用gpu进行计算 通过cpu进行计算 PaddleOCR只需要初始化一次 会将模块加载到内存 会将相关模型下载 如果是第一次使用
ocr = PaddleOCR(usr_angle_cls=True, use_gpu=False)

@app.route('/learn/hello')
def hello_world():
    return 'hello world'

@app.route('/learn/path/<string:name>')
def learn_path(name):
    return 'hello world ' + name

@app.route('/learn/m-get', methods=['GET'])
def learn_get_method():
    age = request.args.get('age')
    name = request.args.get('name')
    logging.info('learn m-get age 是: %s, name 是: %s', age, name)
    return 'SUCCESS', 200

@app.route('/learn/m-post', methods=['POST'])
def learn_post():
    data = request.data.decode('utf-8')
    logging.info('learn m-post data : %s', data)
    data = json.loads(data)
    age = data.get('age')
    name = data.get('name')
    logging.info('learn m-post age 是: %s, name 是: %s', age, name)
    return jsonify(data), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=5000)
